﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using testExcel;
using System.IO.Ports;
using System.Threading;
using System.Xml;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using Pasteles.Controler;
using Pasteles.DataBase;

namespace Pasteles
{
    public partial class CustomerIDfromMySQLTB : Form
    {

        // 
       private int ReceiptsuptoNow = 0;
        // public DataSet ds = new DataSet();
        public StreamWriter log;
        public string logfile = "CashierFormLog.txt";
        public StringProcessing objStringProcessor = new StringProcessing();
        
        public static Printer objPrinter = new Printer("CashierFormLog.txt");

        Connection cnn = new Connection("config.xml");
        public DataTable db = new DataTable(); //db0, sQuery0
        public DataTable dbTemp = new DataTable(); //db0, sQuery0
        public DataTable db1 = new DataTable(); //db1, sQuery1
        public DataTable db2 = new DataTable(); //db2, sQuery2
        public DataTable db3 = new DataTable(); //db3, sQuery3

        public DataTable addDB = new DataTable();
        public DataView dv;
        public DataView addDV;
        public DataView dvtest;
        SerialPort _serialPort;

        DataTable _Hoa_Don = new DataTable();
        DataTable _Chi_Tiet_Hoa_Don = new DataTable();
        DataTable Hoa_Don = new DataTable();
        DataTable Chi_Tiet_Hoa_Don = new DataTable();
        public long receiptNo;
        
        //MySqlConnection connection;
        string sMaNhanVien = "";
        string sShopID = "";

        public CustomerIDfromMySQLTB()
        {
            InitializeComponent();
            CheckTables();//load bàn
            
            NgayGiaoDateTimePicker.CustomFormat = "MM-dd-yyyy HH:mm";

            lbl_ReceiptuptoNow.Text = ReceiptsuptoNow.ToString();//moi dau ca, tong so receipt trong ca = 0
            lbl_MaNV.Text = LoginForm.manv;

            sMaNhanVien = LoginForm.manv;
            sShopID = LoginForm.sShopID;
            this.createConection();
            ListviewLoad(db, false);//load vào lv_product phần bánh mì,khi người dùng chưa thao tác lần đầu
            _Hoa_Don = new DataTable();
            _Hoa_Don.Columns.Add("Ma_Hoa_Don", typeof(double));
            _Hoa_Don.Columns.Add("Ngay_Lap_Hoa_Don", typeof(DateTime));
            _Hoa_Don.Columns.Add("Tong_Gia_Tri_Hoa_Don", typeof(double));
            _Hoa_Don.Columns.Add("Chiet_Khau", typeof(int));
            //_Hoa_Don.PrimaryKey = new DataColumn[] {_Hoa_Don.Columns["Ma_Hoa_Don"] };

            _Chi_Tiet_Hoa_Don = new DataTable();
            _Chi_Tiet_Hoa_Don.Columns.Add("Ma_Nhan_Vien", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("Ma_Phong_Ban", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("Ma_Banh", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("Ma_Hoa_Don", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("Ma_Don_Dat_Hang", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("So_Luong_Ban", typeof(int));
            _Chi_Tiet_Hoa_Don.Columns.Add("Gia_Ban", typeof(double));
            _Chi_Tiet_Hoa_Don.Columns.Add("Thanh_Tien", typeof(double));
            //_Hoa_Don.PrimaryKey = new DataColumn[] { _Hoa_Don.Columns["Ma_Hoa_Don"] };

            Hoa_Don = _Hoa_Don.Clone();
            Chi_Tiet_Hoa_Don = _Chi_Tiet_Hoa_Don.Clone();
            //MessageBox.Show("Cashier form load OK");
        }



        //------------------------------Controler-----------------------------//
      

        private void loadBanhFromMySQLtoDataTable(String sQuery, ref DataTable datatable)
        {
            try
            {
                datatable = cnn.excecuteQueryToDataTable(sQuery);
                //MessageBox.Show(datatable.Columns[0].ColumnName);
                datatable.Columns[0].ColumnName = "ID";

            }
            catch (Exception ex)
            {
                MessageBox.Show("Load banh:"+ex.Message);
            }
            

        } // end loadBanhFromMySQLtoDataTable(String sQuery, DataTable datatable) 


        private void createConection()
        {

            string sQuery0 = "select b.MA_BANH, b.TEN_BANH, b.GIA_KINH_DOANH,s.SO_LUONG_TON_QUAY,s.NGAY_LEN_QUAY,s.NGAY_HET_HAN from banh b,san_pham_tai_quay s where b.MA_LOAI_BANH=1 and b.MA_BANH=s.MA_BANH;";
            string sQuery1 = "select b.MA_BANH, b.TEN_BANH, b.GIA_KINH_DOANH,s.SO_LUONG_TON_QUAY,s.NGAY_LEN_QUAY,s.NGAY_HET_HAN from banh b,san_pham_tai_quay s where b.MA_LOAI_BANH=2 and b.MA_BANH=s.MA_BANH;";
            string sQuery2 = "select * from banh where MA_LOAI_BANH=3;";// sandwich, chi show ra, khong co so luong ton quay
            string sQuery3 = "select * from banh where MA_LOAI_BANH=4;";// nuoc ngot, chi show ra, khong co so luong ton quay
            string sQuery4 = "select * from san_pham_tai_quay;";
            try
            {
                loadBanhFromMySQLtoDataTable(sQuery0, ref db);
                loadBanhFromMySQLtoDataTable(sQuery1, ref db1);
                loadBanhFromMySQLtoDataTable(sQuery2, ref db2);
                loadBanhFromMySQLtoDataTable(sQuery3, ref db3);
                loadBanhFromMySQLtoDataTable(sQuery4, ref dbTemp);
            }
            catch (MySqlException ex)
            {
                MessageBox.Show("SQL Error: " + ex.Message);
            }
            //addDB = db.Clone(); //DataTable 
            Reload_dataTable();
            //set primary key cho cac datatable, de tien cho viec tim kiem ve sau
            db3.PrimaryKey = new DataColumn[] { db3.Columns["ID"] };
            db.PrimaryKey = new DataColumn[] { db.Columns["NGAY_LEN_QUAY"] };
            db1.PrimaryKey = new DataColumn[] { db1.Columns["NGAY_LEN_QUAY"] };
            db2.PrimaryKey = new DataColumn[] { db2.Columns["ID"] };
        }

        //---------------------------------------------------------------Event Handle---------------------------------------------------------------------------------//
        #region
        //--------------------ListboxEvent------------------------------

        //--------------------New ListboxEvent------------------------------
  

        #endregion
        //---------------------DataGridEvent----------------------
        private void ReceiptDatagrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //double id = (double)ReceiptDatagrid.CurrentRow.Cells[1].Value;
            try
            {
                int id = int.Parse(ReceiptDatagrid.CurrentRow.Cells[1].Value.ToString());


                if (e.ColumnIndex == 0)
                {
                    ReceiptDatagrid.Rows.RemoveAt(e.RowIndex);

                    //------------------------------CheckOut-------------------------------------//
                    float total = 0;
                    for (int i = 0; i < ReceiptDatagrid.Rows.Count; i++)
                    {
                        total += (float.Parse(ReceiptDatagrid.Rows[i].Cells["Cost"].Value.ToString()) - float.Parse(ReceiptDatagrid.Rows[i].Cells["Cost"].Value.ToString()) *
                       int.Parse(ReceiptDatagrid.Rows[i].Cells["Off%"].Value.ToString()) / 100) *
                       int.Parse(ReceiptDatagrid.Rows[i].Cells["Quantity"].Value.ToString())
                       ;//total=(Cost-Cost*%)*Quantity
                    }
                    tb_Total.Text = String.Format("{0:0,0.##}", double.Parse(total.ToString()));
                    if (tb_Total.Text == "00")
                    {
                        tb_Total.Text = "";
                    }
                    //--------------------------------------------------------------------------//
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid number, must be NUMBER");
            }


        }

        private void ReceiptDatagrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }


        private void btn_CheckOut_Click(object sender, EventArgs e)
        {
            if (ReceiptDatagrid.RowCount < 1)
            {
                MessageBox.Show("Không có sản phẩm nào");
                return;
            }

            ReceiptsuptoNow++;//in them 1 hoa don, tang tong so hoa don trong ca len 1
            lbl_ReceiptuptoNow.Text = ReceiptsuptoNow.ToString();//hien thi tong so hoa don trong ca

            int tableNo=int.Parse(comBox_tableNo.Text);
            if (tableNo==0)
            {
                receiptNo = getLatestReceiptID() + 1;
                MessageBox.Show("In Hóa Đơn Số: " + receiptNo.ToString());
                lv_product.Enabled = false;
                tb_CustomerCash.ReadOnly = true;
                btn_CheckOut.Enabled = false;

                DateTime curDate = DateTime.Now;
                double totalCost = double.Parse(tb_Total.Text);//Chu y
                string sTotalCostToPrint = tb_Total.Text;

                int discount = 1;//Chu y

                long id = receiptNo;
                
                lbl_ReceiptNo.Text = receiptNo.ToString();
                Hoa_Don.Rows.Add(id, curDate, totalCost, discount);
                string sNgayLapHoaDon = curDate.ToString("yyyy-MM-dd HH:mm:ss");

                String sSaveBillQuery = "INSERT INTO hoa_don " +
                                          "(MA_HOA_DON, NGAY_LAP_HOA_DON, TONG_GIA_TRI_HOA_DON, " +
                                          "CHIET_KHAU) VALUES (" + id + ", '" + sNgayLapHoaDon + "', " +
                                          totalCost + "," + discount + ");";
                insertIntoMySQL(sSaveBillQuery);
                objPrinter.logToFile(sSaveBillQuery);
                //Hoa_Don.Reset();            
                //Hoa_Don = _Hoa_Don.Clone();


                string maNV = lbl_MaNV.Text;
                long maHoaDon = id;
                int maPhongBan = 1;
                int maDonDatHang = 1;
                int maBanh;
                int soLuongBan;
                int giaBan;
                int saleOff;
                long thanhTien;
                string printString = "";

                int countRow = addDB.Rows.Count;
                string sQuery2 = "";
                string sQuery3InsertToView = "";

                foreach (DataGridViewRow row in ReceiptDatagrid.Rows)
                {
                    if (int.Parse(row.Cells["Table"].Value.ToString()) == 0)
                    {
                        maBanh = int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["ID"].Value.ToString());
                        soLuongBan = int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Quantity"].Value.ToString());
                        giaBan = int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Cost"].Value.ToString());
                        saleOff = int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Off%"].Value.ToString());
                        thanhTien = soLuongBan * giaBan * (100-saleOff)/100;
                        maPhongBan = int.Parse(LoginForm.sShopID);
                        maDonDatHang = 1;

                        sQuery2 = "INSERT INTO  chi_tiet_hoa_don (MA_NHAN_VIEN, MA_PHONG_BAN, MA_BANH, " +
                            "MA_HOA_DON, MA_DON_DAT_HANG, SO_LUONG_BAN, GIA_BAN, THANH_TIEN,SALE_OFF,DA_XOA) VALUES (" +
                            maNV + "," + maPhongBan + "," + maBanh + "," + maHoaDon + "," +
                            maDonDatHang + "," + soLuongBan + "," + giaBan + "," + thanhTien + "," + saleOff + ",0);";
                        objPrinter.logToFile(sQuery2);
                        insertIntoMySQL(sQuery2);
                    }
                }

                //Phan Code cu, dung de doi chieu voi code phia neu neu co sua loi sau nay
                #region
                //for (int i = 0; i < countRow; i++)
                //{
                //    //maBanh = (double)addDB.Rows[i]["ID"];
                //    maBanh = Convert.ToDouble(addDB.Rows[i]["ID"].ToString());
                //    //soLuongBan = (int)addDB.Rows[i]["Quantity"];
                //    soLuongBan = Convert.ToInt32(addDB.Rows[i]["Quantity"].ToString());

                //    //giaBan = (double)addDB.Rows[i]["Price"];
                //    giaBan = Convert.ToDouble(addDB.Rows[i]["Price"].ToString());

                //    thanhTien = soLuongBan * giaBan;
                //    maPhongBan = Convert.ToDouble(LoginForm.sShopID);
                //    maDonDatHang = 1;
                //    string sSaleOff = addDB.Rows[i]["Off (%)"].ToString();
                //    if (sSaleOff.Length > 0)
                //    {
                //        saleOff = Convert.ToDouble(sSaleOff);
                //    }
                //    else saleOff = 0;

                //    //Chi_Tiet_Hoa_Don.Rows.Add(maNV,maPhongBan,maBanh,maHoaDon,maDonDatHang,soLuongBan,giaBan,thanhTien);
                //    sQuery2 = "INSERT INTO  chi_tiet_hoa_don (MA_NHAN_VIEN, MA_PHONG_BAN, MA_BANH, " +
                //        "MA_HOA_DON, MA_DON_DAT_HANG, SO_LUONG_BAN, GIA_BAN, THANH_TIEN,SALE_OFF,DA_XOA) VALUES (" +
                //        maNV + "," + maPhongBan + "," + maBanh + "," + maHoaDon + "," +
                //        maDonDatHang + "," + soLuongBan + "," + giaBan + "," + thanhTien + "," + saleOff + ",0);";
                //    objPrinter.logToFile(sQuery2);
                //    insertIntoMySQL(sQuery2);
                //}
                #endregion
                string sCash = tb_CustomerCash.Text;
                string sChange = tb_Change.Text;
                tb_CustomerCash.Text = "";
                tb_Change.Text = "";
                tb_Total.Text = "";
                //reset gridview
                ReceiptDatagrid.DataSource = addDB;

                //In hoa don 
                string sSecondBill = "", sFirstBill = "";
                string s1 = "", s2 = "", s3 = "", s4 = "";
                try
                {
                    string sBillHeader = cnn.preparingBillHeader();
                    objPrinter.logToFile(sBillHeader + sBillHeader.Length.ToString());
                    objPrinter.safePrinting(sBillHeader);
                    objPrinter.safePrinting("##############################\r\n");
                    //MessageBox.Show(sBillHeader.ToString());
                    string sBillDetails = "";
                    for (int i = 0; i < addDB.Rows.Count; i++)
                    {
                        if (int.Parse(addDB.Rows[i]["Table"].ToString()) == 0)//In hoa don cho khach mua ve ngay
                        {
                            int tempGia = (Convert.ToInt32(addDB.Rows[i]["Cost"]) * (100-Convert.ToInt32(addDB.Rows[i]["Off%"]))/100);
                            string gia = objStringProcessor.cutNo(tempGia.ToString());
                            printString = objStringProcessor.stringReceipt(addDB.Rows[i]["Name"].ToString(), addDB.Rows[i]["Quantity"].ToString(), gia);
                            sBillDetails = sBillDetails + printString;
                        }
                    }
                    objPrinter.safePrinting(sBillDetails);
                    objPrinter.logToFile(sBillDetails + sBillDetails.Length.ToString());
                    //MessageBox.Show(sBillDetails.ToString());
                    string sBillSummary = "------------------------------\r\n" +
                                "TONG CONG:\r\n" + sTotalCostToPrint + "\r\n" +
                                "TIEN MAT:\r\n" + sCash + "\r\n" +
                                "THOI LAI:\r\n" + sChange + "\r\n";
                    objPrinter.logToFile(sBillSummary + sBillSummary.Length.ToString());
                    objPrinter.safePrinting(sBillSummary);
                    //MessageBox.Show(sBillSummary.ToString());
                    string sBillFooter = "------------------------------\r\n" + "       CAM ON QUY KHACH\r\n" + "         HEN GAP LAI !\r\n"; ;
                    objPrinter.safePrinting(sBillFooter);
                    objPrinter.logToFile(sBillFooter + sBillFooter.Length.ToString());
                    objPrinter.safePrinting("\r\n\r\n");
                    //MessageBox.Show(sBillFooter.ToString());
                    //sSecondBill = sBillHeader + sBillSummary + sBillDetails + sBillFooter;
                    s1 = sBillHeader;
                    s2 = sBillDetails;
                    s3 = sBillSummary;
                    s4 = sBillFooter;
                    sFirstBill = sSecondBill;
                    //MessageBox.Show("First bill, length ="+sFirstBill.Length+"\r\n" + sFirstBill);
                    objPrinter.logToFile(sFirstBill);
                    //flowControlPrinting(sFirstBill);
                    //safePrinting(sFirstBill);
                }
                catch (Exception ex)
                {
                    //MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
                    objPrinter.logToFile("Error opening/writing to serial port :: " + ex.Message);

                }
                MessageBox.Show("Đã in hóa đơn: "+receiptNo);

                if (MessageBox.Show("Print another receipt?",
                                    "Receipt is printed",
                                    MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    string sNewSecondBill = "\r\nSecond bill\r\n" + sSecondBill;
                    //safePrinting(sNewSecondBill);
                    objPrinter.logToFile(sNewSecondBill.ToString());
                    objPrinter.logToFile(s1 + s1.Length.ToString());
                    objPrinter.safePrinting(s1);
                    objPrinter.safePrinting("##############################\r\n");
                    objPrinter.logToFile(s2 + s2.Length.ToString());
                    objPrinter.safePrinting(s2);
                    objPrinter.logToFile(s3 + s3.Length.ToString());
                    objPrinter.safePrinting(s3);
                    objPrinter.logToFile(s4 + s4.Length.ToString());
                    objPrinter.safePrinting(s4);
                    objPrinter.safePrinting("\r\n\r\n");


                }
                lv_product.Enabled = true;
                tb_CustomerCash.ReadOnly = false;
                btn_CheckOut.Enabled = false;
                AddCaketo_table();
                receiptNo++;
            }
            else
            {
                foreach (DataGridViewRow row in ReceiptDatagrid.Rows)
                {
                    row.Cells["Table"].Value = tableNo.ToString();
                }
                AddCaketo_table();

                MessageBox.Show("Đã ghi hóa đơn vào bàn "+tableNo.ToString());
            }
            //reset addDB
            addDB.Clear();
            comBox_tableNo.Text = "0";
            tb_Total.Text = "";
            tc_product.SelectedIndex = 0;
            CheckTables();
            xem_doanh_thu();
        }
        private void xem_doanh_thu()
        {
            string s_query = "select sum(tong_gia_tri_hoa_don) as tong from hoa_don where NGAY_LAP_HOA_DON between '" + DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00' and '" + DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59';";
            objPrinter.logToFile(s_query);
            DataTable dt = cnn.excecuteQueryToDataTable(s_query);
            lb_totalsales.Text = dt.Rows[0]["tong"].ToString();
            MessageBox.Show(dt.Rows[0]["tong"].ToString());
        }
        //-----------------TextboxEvent---------------------
        private void tb_CustomerCash_KeyDown(object sender, KeyEventArgs e)//Khoa ban phim chi cho nhap so
        {
            this.validateNum(e);
        }

        private void tb_CustomerCash_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {
                e.Handled = true;
            }
        }

        private void tb_Total_TextChanged(object sender, EventArgs e)
        {
            if (tb_Total.Text != "")
            {

                btn_CheckOut.Enabled = true;
            }
        }

        private void tb_CustomerCash_TextChanged(object sender, EventArgs e)
        {
            if (tb_CustomerCash.Text.ToString().Length > 3)
            {
                try
                {
                    objStringProcessor.cutNo(tb_CustomerCash);
                    if (tb_Total.Text != "" && tb_CustomerCash.Text != "")
                    {
                        if (double.Parse(tb_Total.Text.ToString()) <= double.Parse(tb_CustomerCash.Text.ToString()))
                        {

                            btn_CheckOut.Enabled = true;
                            //---------------ChangePay-------------------------
                            double change = Convert.ToDouble(tb_CustomerCash.Text) - Convert.ToDouble(tb_Total.Text);
                            tb_Change.Text = String.Format("{0:0,0.##}", double.Parse(change.ToString()));
                            //-------------------------------------------------
                        }
                        else
                        {

                            btn_CheckOut.Enabled = false;
                        }
                    }
                    else
                    {

                        btn_CheckOut.Enabled = false;
                    }
                }
                catch (Exception ex)
                {
                }
            }

        }

        //------------FormEvent-------------------
        private void CashierForm_Load(object sender, EventArgs e)
        {
            this.BringToFront();

            receiptNo = getLatestReceiptID() + 1;
            
            lbl_ReceiptNo.Text = receiptNo.ToString();
            objPrinter._serialPort = cnn.preparingSerialPort();
            
            /////////////////////////////////////////////////////////////////////////////
            ////////NEW CODE
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("temp.xml");
                XmlNode node = xmlDoc.SelectSingleNode("Pasteles/StartTime");
                if (node.InnerText.Equals("1"))
                {
                    node.InnerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    xmlDoc.Save("temp.xml");
                    //MessageBox.Show("???");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            xem_doanh_thu();
            /////////////////////////////////////////////////////////////////////////////NEW CODE
        }


        //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//

        //------------------------------------------------------------------------------------Validate-----------------------------------------------------------------------------------//

        private bool nonNumberEntered = false;//bien flag dung de khoa ban phim nhap lieu
        private void validateNum(KeyEventArgs e)//Ham chi cho phep nhap so nguyen duong
        {
            nonNumberEntered = false;
            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {
                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {
                    if (e.KeyCode != Keys.Back)
                    {

                        nonNumberEntered = true;
                    }
                }
            }
            if (Control.ModifierKeys == Keys.Shift)
            {
                nonNumberEntered = true;
            }
        }

        private void listProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            

            //pb_Product.ImageLocation = Application.StartupPath + "\\image\\" + sImageName;
        }




        //--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------//
       

        //--------------------------------------------------//
       


        private void insertIntoMySQL(string sQuery)
        {
            try
            {
                cnn.excecuteQuery(sQuery);
            }
            catch (Exception error)
            {
                MessageBox.Show("Insert Error: " + error.ToString());
            }
        }

        private void ShiftReportsBTN_Click(object sender, EventArgs e)
        {

        }

        private void CashierForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult myDialogResult;
            myDialogResult = MessageBox.Show("Are you sure to exit?", "Exit", MessageBoxButtons.YesNo);
            if (myDialogResult == DialogResult.Yes)
            {
                //connection.Close();
                objPrinter._serialPort.Close();
                e.Cancel = false;
                LoginForm logForm = new LoginForm();
                logForm.Visible = true;

            }
            else
            {
                e.Cancel = true;
            }
            //System.Threading.Thread.Sleep(100);
        }


        private void DeleteReportsBtn_Click(object sender, EventArgs e)
        {

        }


        private void deleteChiTietHoaDon(string sQuery)
        {
            try
            {
                cnn.excecuteQuery(sQuery);
                MessageBox.Show("Reports have been deleted");

            }
            catch (Exception error)
            {
                MessageBox.Show("Delete Error: " + error.ToString());
            }
            //connection.Close();

        }

        private void CashDrawerBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (!_serialPort.IsOpen)
                    _serialPort.Open();
                string sOpenSesame = "Open Sesame !!!!" + (char)0xFF;
                _serialPort.Write(sOpenSesame);

                for (int i = 0; i < 100; i++)
                {
                    _serialPort.Write(sOpenSesame);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Open cash error");
            }
        }
        ///////////////////////////////////
        


        ///////////////////////////////////
        //
        /*
        private void flowControlPrinting(string sStringToPrint)
        {
            logToFile("\r\n Flow control printing\r\n");
            if (!_serialPort.IsOpen)
                _serialPort.Open();
            _serialPort.Handshake = System.IO.Ports.Handshake.RequestToSend;
            _serialPort.Write(sStringToPrint);
            
        }
        */
        

        private void readDataFromDatabase(string sQuery)
        {

        }

        private long getLatestOrderID()
        {
            long lOrderID = 0;
            string sQuery = "select max(don_dat_hang.ma_don_dat_hang) from don_dat_hang;";
            try
            {

                foreach (DataRow dr in cnn.excecuteQueryToDataTable(sQuery).Rows)
                {
                    lOrderID =Convert.ToInt64(dr[0]);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("No order ID: " + ex.ToString());
            }
            //connection.Close();
            return lOrderID;
        }
        private long getLatestReceiptID()
        {
            long lReceiptNoLocal = 0;
            string sQuery = "select max(hoa_don.ma_hoa_don) from hoa_don;";
            try
            {

                foreach (DataRow dr in cnn.excecuteQueryToDataTable(sQuery).Rows)
                {
                    lReceiptNoLocal = Convert.ToInt64(dr[0]);
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Push data error: " + ex.ToString());
            }
            //connection.Close();
            return lReceiptNoLocal;
        }



        private void ManageOrderBtnClick(object sender, EventArgs e)
        {
            DonDatHangForm orderForm = new DonDatHangForm();
            orderForm.Activate();
            orderForm.ShowDialog();


        }

        private void CustomerDepositTB_KeyDown(object sender, KeyEventArgs e)
        {
            this.validateNum(e);
        }
        private void CustomerDepositTB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (nonNumberEntered == true)
            {
                e.Handled = true;
            }
            if (e.KeyChar == 13)
            {
                btn_PrintOrder_Click(sender, e);
            }

        }
  
        private void NewOrderBtn_Click(object sender, EventArgs e)
        {
            NewOrderBtn.Visible = false;
            btn_CancelOrder.Visible = true;
            btn_PrintOrder.Enabled = true;
            CustomerIDCombo.Visible = true;
            tb_CustomerCash.ReadOnly = true;
            CustomerDepositTB.Enabled = true;
            Int32 orderID = 0;
            string showOrderID = "call hien_ma_don_hang_cuoi()";
            try
            {
                objPrinter.logToFile("Show ID Order\r\n");
                objPrinter.logToFile(showOrderID);
                orderID = Convert.ToInt32(cnn.excecuteQueryToDataTable(showOrderID).Rows[0][0]);

                long sOrderID = Convert.ToInt64(orderID.ToString());
                sOrderID++;
                txt_OrderID.Text = sOrderID.ToString();
            }
            catch (Exception error)
            {
                MessageBox.Show("Push data error: " + error.ToString());
            }
            //connection.Close();
            btn_PrintOrder.Visible = true;
        }
        private void btn_PrintOrder_Click(object sender, EventArgs e)
        {
            if (ReceiptDatagrid.RowCount!=0)
            {
                try
                {
                    //reset gridview
                    ReceiptDatagrid.DataSource = addDB;
                   lv_product.Enabled = false;
                    
                    DateTime curDate = DateTime.Now;
                    string sTotalOrder = tb_Total.Text;
                    string Deposit = CustomerDepositTB.Text;
                    sTotalOrder = sTotalOrder.Replace(",", "");

                    long totalCost = long.Parse(sTotalOrder);
                    double sDeposit = 0;
                    if (CustomerDepositTB.Text.ToString().Length == 0)
                    {
                        sDeposit = 0;
                    }
                    else
                    {
                        sDeposit = double.Parse(CustomerDepositTB.Text.ToString());
                    }
                    int sSateCheckOut = 0;
                    if (sDeposit == totalCost)
                    {
                        sSateCheckOut = 1;
                    }

                    long orderID = long.Parse(txt_OrderID.Text.ToString());
                    lbl_ReceiptNo.Text = "Order ID: " + orderID.ToString();
                    string sNgayDatHang = curDate.ToString("yyyy-MM-dd HH:mm");
                    //MessageBox.Show(sNgayDatHang.ToString());
                    string sNgayGiao = NgayGiaoDateTimePicker.Value.ToString("yyyy-MM-dd HH:mm");
                 
                    string sPrintOrder = "##############################\r\n";
                    //logToFile(sPrintOrder +": "+sPrintOrder.Length.ToString());
                    objPrinter.logToFile(sPrintOrder + ": " + sPrintOrder.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder);
                    string sPrintOrder1 = "New Order:" + orderID.ToString() + "\r\n";
                    objPrinter.logToFile(sPrintOrder1 + ": " + sPrintOrder1.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder1);
                    string sPrintOrder2 = "Ngay dat: " + sNgayDatHang + "\r\n";
                    objPrinter.logToFile(sPrintOrder2 + ": " + sPrintOrder2.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder2);
                    string sPrintOrder3 = "Ngay giao: " + sNgayGiao + "\r\n";
                    objPrinter.logToFile(sPrintOrder3 + ": " + sPrintOrder3.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder3);
                    string sPrintOrder4 = "Tong gia tri: " + objStringProcessor.cutNo(sTotalOrder) + "VNĐ\r\n";
                    objPrinter.logToFile(sPrintOrder4 + ": " + sPrintOrder4.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder4);
                    string sPrintOrder5 = "Dat coc: " + objStringProcessor.cutNo(Deposit) + "VNĐ\r\n";
                    objPrinter.logToFile(sPrintOrder5 + ": " + sPrintOrder5.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder5);
                    string sQuery = "insert into don_dat_hang (ngay_dat_hang,ngay_giao_hang,tinh_trang_thanh_toan,deposit,tong_gia_tri_don_hang)" +
                        " values ('" + sNgayDatHang + "','" + sNgayGiao + "',"+sSateCheckOut+", " +
                        sDeposit + ", " + totalCost + ");";

                    insertIntoMySQL(sQuery);

                    // Insert chi_tiet_don_dat_hang
                    int countRow = addDB.Rows.Count;
                    String sQuery2 = "";
                    string sCustomerID = CustomerIDCombo.Text;
                    double maBanh;
                    int soLuongBan;
                    double giaBan;
                    double thanhTien;
                    string tenbanh = "";
                    //double saleOff;
                    string sPrintOrder6 = "";
                    for (int i = 0; i < countRow; i++)
                    {
                        maBanh = Convert.ToDouble(addDB.Rows[i]["ID"].ToString());
                        tenbanh = Convert.ToString(addDB.Rows[i]["Name"].ToString());
                        soLuongBan = Convert.ToInt32(addDB.Rows[i]["Quantity"].ToString());
                        giaBan = Convert.ToDouble(addDB.Rows[i]["Cost"].ToString());
                    
                        thanhTien = soLuongBan * giaBan;
                  
                        
                        sPrintOrder6 = sPrintOrder6 + objStringProcessor.stringOrder(maBanh.ToString(), tenbanh.ToString(), soLuongBan.ToString()) + "\r\n";
              
                        sQuery2 = " insert into  chi_tiet_don_dat_hang  " +
                            " (ma_nhan_vien,ma_banh , ma_phong_ban,ma_don_dat_hang,ma_khach_hang,so_luong_dat_hang)" +
                             " values (" + sMaNhanVien + "," + maBanh + "," + sShopID + "," + orderID + "," +
                             sCustomerID + "," + soLuongBan + ");";
                        insertIntoMySQL(sQuery2);
                    }
                    objPrinter.logToFile(sPrintOrder6 + ": " + sPrintOrder6.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder6);
                    string sPrintOrder7 = "Please send to Kitchen!!!\r\n";
                    objPrinter.logToFile(sPrintOrder7 + ": " + sPrintOrder7.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder7);
                    string sPrintOrder8 = "Due date is: " + sNgayGiao+"\r\n";
                    objPrinter.logToFile(sPrintOrder8 + ": " + sPrintOrder8.Length.ToString());
                    objPrinter.safePrinting(sPrintOrder8);
                    objPrinter.safePrinting("\r\n\r\n");
                    //safePrinting(sPrintOrder);
                   // logToFile(sPrintOrder);

                    MessageBox.Show("Đã in đơn hàng!!");
                    if (MessageBox.Show("Print another Order?",
                                "Order is printed",
                                MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        objPrinter.logToFile("\r\n\r\n\r\n");
                        objPrinter.logToFile("Second Order \r\n");
                        objPrinter.logToFile(sPrintOrder + ": " + sPrintOrder.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder);
                        objPrinter.logToFile(sPrintOrder1 + ": " + sPrintOrder1.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder1);
                        objPrinter.logToFile(sPrintOrder2 + ": " + sPrintOrder2.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder2);
                        objPrinter.logToFile(sPrintOrder3 + ": " + sPrintOrder3.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder3);
                        objPrinter.logToFile(sPrintOrder4 + ": " + sPrintOrder4.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder4);
                        objPrinter.logToFile(sPrintOrder5 + ": " + sPrintOrder5.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder5);
                        objPrinter.logToFile(sPrintOrder6 + ": " + sPrintOrder6.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder6);
                        objPrinter.logToFile(sPrintOrder7 + ": " + sPrintOrder7.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder7);
                        objPrinter.logToFile(sPrintOrder8 + ": " + sPrintOrder8.Length.ToString());
                        objPrinter.safePrinting(sPrintOrder8);
                    }
                    //enable
                    lv_product.Enabled = true;
                    tb_CustomerCash.ReadOnly = false;
                    btn_CheckOut.Enabled = false;
                    //reset addDB
                    addDB.Clear();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("New order Error:" + ex.ToString());

                }
                NewOrderBtn.Visible = true;
                btn_CancelOrder.Visible = false;
                btn_PrintOrder.Enabled = false;
                txt_OrderID.Text = "";
                tb_CustomerCash.ReadOnly = false;
                CustomerDepositTB.Enabled = false;
                CustomerDepositTB.Text = "";
                tb_Total.Text = "";
            }
            else
            {
                MessageBox.Show("Xin lỗi, bạn chưa chọn sản phẩm!!!");
            }
        }

        private void CustomerDepositTB_TextChanged(object sender, EventArgs e)
        {
            objStringProcessor.cutNo(CustomerDepositTB);
            if (CustomerDepositTB.Text != "")
            {
                if (double.Parse(tb_Total.Text.ToString()) <= double.Parse(CustomerDepositTB.Text.ToString()))
                {
                    CustomerDepositTB.Text = tb_Total.Text;
                }
            }
        }

        private void ReceiptDatagrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
                double id = Convert.ToDouble(ReceiptDatagrid.CurrentRow.Cells["ID"].Value.ToString());
                int quantity = Convert.ToInt32(ReceiptDatagrid.CurrentRow.Cells["Quantity"].Value.ToString());
                double price = Convert.ToDouble(ReceiptDatagrid.CurrentRow.Cells["Cost"].Value.ToString());

                double offPrice = Convert.ToDouble(ReceiptDatagrid.CurrentRow.Cells[6].Value.ToString());

                //------------------------------CheckOut-------------------------------------//
                float total = 0;
                foreach (DataGridViewRow row in ReceiptDatagrid.Rows)//tim trong ReceiptdataGrid, neu Table=0 thi moi + tien vao Total;
                    if (int.Parse(row.Cells["Table"].Value.ToString()) == 0)
              
                {
                    total += (float.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Cost"].Value.ToString()) - float.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Cost"].Value.ToString()) *
                        int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Off%"].Value.ToString()) / 100) *
                        int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Quantity"].Value.ToString())
                        ;//total=(Cost-Cost*%)*Quantity
                }
                tb_Total.Text = String.Format("{0:0,0.##}", double.Parse(total.ToString()));
                if (tb_Total.Text == "00")
                {
                    tb_Total.Text = "";
                }
                //--------------------------------------------------------------------------//
        }

        private void btn_CancelOrder_Click(object sender, EventArgs e)
        {
            NewOrderBtn.Visible = true;
            tb_CustomerCash.ReadOnly = false;
            btn_CancelOrder.Visible = false;
            btn_PrintOrder.Enabled = false;
            CustomerDepositTB.Enabled = false;
        }

        private void btnUnimportant_Click(object sender, EventArgs e)
        {
            CashierUnimportantForm cuForm = new CashierUnimportantForm();
            cuForm.Activate();
            cuForm.Show();
        }
        /// <summary>
        /// Hàm này dùng để hiểm thị bàn lên listbox, bàn có khách màu đỏ, không khách màu đen
        /// </summary>
        public void CheckTables()
        {
            lv_checkTables.Clear();
            XmlDocument doc = new XmlDocument();
            doc.Load("OnTable.xml");
            string xPathTable = "/Tables/table";
            XmlNodeList tables = doc.SelectNodes(xPathTable);
            foreach (XmlNode table in tables)
            {
                string id = table.Attributes["id"].Value;
                
                if (table.HasChildNodes)//bàn có khách màu đỏ
                {
                    lv_checkTables.Items.Add("Bàn Số " + id).ForeColor = Color.Red;
                    
                }
                else { lv_checkTables.Items.Add(("Bàn Số " + id)); }
              //  lv_checkTables.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            }
        }

        private void lv_checkTables_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (lv_checkTables.SelectedItems[0].ForeColor == Color.Red)
            {
                int id=lv_checkTables.SelectedItems[0].Index+1;
                CheckTables ChkTb = new CheckTables(id);
                ChkTb.ShowDialog();
                CheckTables();
                xem_doanh_thu();
            }
        }

        private void tc_product_Selected(object sender, TabControlEventArgs e)
        {
            switch (e.TabPageIndex)
            {
                case 0:
                    ListviewLoad(db, false);
                    break;
                case 1:
                    ListviewLoad(db1, false);break;
                case 2:
                    ListviewLoad(db2, true);break;
                case 3:
                    ListviewLoad(db, false);break;
                case 4:
                    ListviewLoad(db3, true);break;
            }
        }
        /// <summary>
        /// Lấy du lieu tu datatable load vao lv_product, có vấn đề về sửa lỗi: xem hàm: loadBanhFromMySQLtoDataTable(String sQuery, ref DataTable datatable)
        /// và hàm Createconnection()
        /// </summary>
        /// <param name="dt">db,db1,db2,db3</param>
        /// <param name="fruit">true:xu ly rieng cho truong hop fruit,false:cac truong hop con lai</param>
        private void ListviewLoad(DataTable dt, bool fruit)
        {
            lv_product.Clear();
            dt.DefaultView.Sort = "TEN_BANH ASC";
            if (fruit==true)
            {
                lv_product.Columns.Add("name", "Tên Sản Phẩm", 280);
                lv_product.Columns.Add("ID", "ID", 0);
                lv_product.Columns.Add("Cost", "Cost", 0);

                foreach(DataRow row in dt.Rows)
                {
                    string name = row["TEN_BANH"].ToString();
                    string id = row["ID"].ToString();
                    string cost = row["GIA_KINH_DOANH"].ToString();
                    string[] item = { name,id,cost};
                    ListViewItem lvi = new ListViewItem(item);
                    lv_product.Items.Add(lvi);
                }
            }
            else 
            {
                lv_product.Columns.Add("name", "Tên Sản Phẩm", 280);
                lv_product.Columns.Add("quantity", "Số Lượng Còn", 128);
                lv_product.Columns.Add("ID", "ID", 0);
                lv_product.Columns.Add("date", "date", 0);
                lv_product.Columns.Add("Cost", "Cost", 0);
                foreach (DataRow row in dt.Rows)
                {
                    string name = row["TEN_BANH"].ToString();
                    string quantity = row["SO_LUONG_TON_QUAY"].ToString();
                    string id = row["ID"].ToString();
                    string date = row["NGAY_LEN_QUAY"].ToString();
                    string cost = row["GIA_KINH_DOANH"].ToString();
                    string[] item = { name,quantity, id ,date,cost};
                    ListViewItem lvi = new ListViewItem(item);
                    lv_product.Items.Add(lvi);
                }
            }
        }

        //sự kiện người dùng doublelcik vào sản phẩm, sẽ xuất sang receiptdatagrid
        private void lv_product_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int tabindex = tc_product.SelectedIndex;//lấy vị trí tab hiện hành,cho biết đang ở loại bánh nào
            int lv_index=lv_product.SelectedItems[0].Index;//lấy vị trí dòng hiện hành của lv_product
            string id="";//lấy id sản phẩm
            string date="";//lay NGAY_LEN_QUAY, day la gia tri rat huu dung vi no unique
            string cost = "";//lay Cost, bien nay dung de xu ly dac biet cho truong hop SW TC
            if (tabindex == 4||tabindex==2)
            {
                id = lv_product.SelectedItems[0].SubItems[1].Text;
            }
            else
            {
                id = lv_product.SelectedItems[0].SubItems[2].Text;
                date=lv_product.SelectedItems[0].SubItems[3].Text;
                cost = lv_product.SelectedItems[0].SubItems[4].Text;
            }

            switch (tabindex)
            {
                case 4:
                case 2:
                    //xem ReceiptDatagrid da co san pham nay chua, chua: tao moi, co roi: cong don`
                    DataRow[] rows = addDB.Select("ID='" + id + "'");
                    if (rows.Length < 1)
                    {
                        DataRow row = addDB.NewRow();
                        row["ID"] = int.Parse(id);
                        row["Name"] = lv_product.SelectedItems[0].SubItems[0].Text;
                        row["Quantity"] = 1;
                        row["Cost"] = int.Parse(lv_product.SelectedItems[0].SubItems[2].Text);
                        row["Type"] = 4;
                        addDB.Rows.Add(row);
                    }
                    else
                    {
                        for (int j = 0; j < ReceiptDatagrid.Rows.Count; j++)
                        {
                            if (ReceiptDatagrid.Rows[j].Cells["ID"].Value.ToString() == id.ToString())
                            {
                                ReceiptDatagrid.Rows[j].Cells["Quantity"].Value = int.Parse(ReceiptDatagrid.Rows[j].Cells["Quantity"].Value.ToString()) + 1; 
                            }
                        }
                    }
                    foreach (DataGridViewRow row in ReceiptDatagrid.Rows)//tim trong ReceiptdataGrid, neu co SW tu chon thi set Cost co the edit duoc;
                        if (int.Parse(row.Cells["Type"].Value.ToString()) == 3)
                        {

                            ReceiptDatagrid.Rows[row.Index].Cells["Cost"].ReadOnly = false;
                            if ((ReceiptDatagrid.Rows.Count - row.Index) >= 2)//Xu ly truong hop loi ky la
                            {
                                for (int i = row.Index + 1; i < ReceiptDatagrid.Rows.Count; i++)
                                {
                                    ReceiptDatagrid.Rows[i].Cells["Cost"].ReadOnly = true;
                                }
                            }
                        }
                        else
                        {
                            ReceiptDatagrid.Rows[row.Index].Cells["Cost"].ReadOnly = true;
                        }
                    break;//fruit

                default: ReceiptDataGrid_load(tabindex, id, cost); break;
            }
            float total = 0;
            foreach (DataGridViewRow row in ReceiptDatagrid.Rows)//tim trong ReceiptdataGrid, neu Table=0 thi moi + tien vao Total;
                if (int.Parse(row.Cells["Table"].Value.ToString()) == 0)
                {
                    total += (float.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Cost"].Value.ToString()) - float.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Cost"].Value.ToString()) *
                        int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Off%"].Value.ToString()) / 100) *
                        int.Parse(ReceiptDatagrid.Rows[row.Index].Cells["Quantity"].Value.ToString())
                        ;//total=(Cost-Cost*%)*Quantity
                }
            tb_Total.Text = String.Format("{0:0,0.##}", double.Parse(total.ToString()));
            if (tb_Total.Text == "00")
            {
                tb_Total.Text = "";
            }
           // dataGridView1.DataSource = addDB;
        }
        /// <summary>
        /// Hàm này dùng để load dữ liệu vào ReceiptDataGrid,hàm này được dùng trong sự kiện duobleclick của lv_product 
        /// </summary>
        /// <param name="tabindex">3:SW tự chọn;0,1,2:các sp còn lại</param>
        /// <param name="id">id san pham</param>
        /// <param name="id">Cost san pham</param>
        private void ReceiptDataGrid_load(int tabindex,string id,string cost)
        {

            DataRow[] rows = addDB.Select("ID="+id+" AND Type="+tabindex+" AND Cost="+cost+"");
                if (rows.Length < 1)
                {
                    DataRow row = addDB.NewRow();
                    row["ID"] = int.Parse(id);
                    if (tabindex == 3)
                    {
                        row["Name"] = "SWTC " + lv_product.SelectedItems[0].SubItems[0].Text;//truong hop SW tu chon
                    }
                    else
                    {
                        row["Name"] =lv_product.SelectedItems[0].SubItems[0].Text;//truong hop khac
                    }
                    row["Quantity"] = 1;
                    row["Cost"] = int.Parse(lv_product.SelectedItems[0].SubItems[4].Text);
                    row["Type"] = tabindex;
                    addDB.Rows.Add(row);
                    
                }
                else {
                    for (int j = 0; j < ReceiptDatagrid.Rows.Count; j++)
                    {
                        if (ReceiptDatagrid.Rows[j].Cells["ID"].Value.ToString() == id && ReceiptDatagrid.Rows[j].Cells["Cost"].Value.ToString() == cost && ReceiptDatagrid.Rows[j].Cells["Type"].Value.ToString() == tabindex.ToString())
                        {
                            ReceiptDatagrid.Rows[j].Cells["Quantity"].Value = int.Parse(ReceiptDatagrid.Rows[j].Cells["Quantity"].Value.ToString()) + 1;
                        }
                        else
                        {
 
                        }
                    }
                }
            foreach(DataGridViewRow row in ReceiptDatagrid.Rows)//tim trong ReceiptdataGrid, neu co SW tu chon thi set Cost co the edit duoc;
                if (int.Parse(row.Cells["Type"].Value.ToString()) == 3)
                {

                    ReceiptDatagrid.Rows[row.Index].Cells["Cost"].ReadOnly = false;
                    if ((ReceiptDatagrid.Rows.Count - row.Index) >= 2)//Xu ly truong hop loi ky la
                    {
                        for (int i = row.Index + 1; i < ReceiptDatagrid.Rows.Count; i++)
                        {
                            ReceiptDatagrid.Rows[i].Cells["Cost"].ReadOnly = true;
                        }
                    }
                }
                else
                {
                    ReceiptDatagrid.Rows[row.Index].Cells["Cost"].ReadOnly = true;
                }

           
        }
        //Tao cau truc cho DataTable addDB, dataTable nay dung de hien thi len ReceiptDataGrid 
        private void Reload_dataTable()
        {
            addDB.Columns.Add("ID", typeof(string));
            addDB.Columns.Add("Name", typeof(string));
            addDB.Columns.Add("Quantity", typeof(int));
            addDB.Columns.Add("Cost", typeof(double));
            addDB.Columns.Add("Off%", typeof(int));
            addDB.Columns["Off%"].DefaultValue = 0;
            addDB.Columns.Add("Table", typeof(int));
            addDB.Columns["Table"].DefaultValue = 0;
            addDB.Columns.Add("Type", typeof(int));
            //addDB.Columns["SALE_OFF"].ColumnName = "Off (%)";
            //addDB.Columns.Add("Off (%)", typeof(double));
            ReceiptDatagrid.DataSource = addDB;
            ReceiptDatagrid.Columns["ID"].Visible = false;
            ReceiptDatagrid.Columns["Type"].ReadOnly = true;
            ReceiptDatagrid.Columns["Cost"].ReadOnly = true;
            ReceiptDatagrid.Columns["Type"].Visible = false;
            ReceiptDatagrid.Columns["Name"].ReadOnly = true;
        }

        private void AddCaketo_table()
        { //  Nhung san pham co Table!=0, nghia la khach tai. ban` thi luu vao` ban`
            XmlDocument doc = new XmlDocument();
            doc.Load("OnTable.xml");

            foreach (DataGridViewRow row in ReceiptDatagrid.Rows)
            {

                string idTable = row.Cells["Table"].Value.ToString();
                string id_cake = row.Cells["ID"].Value.ToString();
                string Name = row.Cells["Name"].Value.ToString();

                string off = row.Cells["Off%"].Value.ToString();
string Cost = (((int.Parse(row.Cells["Cost"].Value.ToString())) * (int.Parse(row.Cells["Off%"].Value.ToString())))/100).ToString();                string Quantity = row.Cells["Quantity"].Value.ToString();
                if (row.Cells["Type"].ToString() != "4" && row.Cells["Type"].ToString() != "2")//thao tac tru banh vao kho
                {
                    string express = "MA_BANH=" + id_cake + "";
                    string sort = "NGAY_LEN_QUAY";
                    DataRow[] process = dbTemp.Select(express, sort);
                    foreach (DataRow _tru in process)
                    {
                        if (int.Parse(_tru["SO_LUONG_TON_QUAY"].ToString()) <= int.Parse(Quantity))
                        {
                            int temp = int.Parse(Quantity) - int.Parse(_tru["SO_LUONG_TON_QUAY"].ToString());
                            Quantity = temp.ToString();
                            string ngay = DateTime.Parse(_tru["NGAY_LEN_QUAY"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                           // MessageBox.Show(ngay);
                            string squery = "DELETE from san_pham_tai_quay WHERE NGAY_LEN_QUAY='" + ngay + "';";

                            cnn.excecuteQuery(squery);
                            Thread.Sleep(500);
                            _tru.Delete();
                        }
                        else
                        {
                            int temp = int.Parse(_tru["SO_LUONG_TON_QUAY"].ToString()) - int.Parse(Quantity);
                            _tru["SO_LUONG_TON_QUAY"] = temp.ToString();
                            string conlai = _tru["SO_LUONG_TON_QUAY"].ToString();

                            string ngay = DateTime.Parse(_tru["NGAY_LEN_QUAY"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                           string squery = "UPDATE san_pham_tai_quay SET SO_LUONG_TON_QUAY=" +
   conlai + " WHERE NGAY_LEN_QUAY='" + ngay + "';";

                            cnn.excecuteQuery(squery);
                            Thread.Sleep(500);
                            break;
                        }
                    }
                }

                if (int.Parse(row.Cells["Table"].Value.ToString()) != 0)
                {
                    string xPath = "//table[@id='" + idTable + "']";
                    string xPath1 = "//table[@id='" + idTable + "']/pastry[@name='" + Name + "']";
                    XmlNode Node = doc.SelectSingleNode(xPath);
                    XmlNodeList Nodelist = doc.SelectNodes(xPath1);
                    if (Nodelist.Count > 0)//bánh này đã có trong bàn
                    {

                        foreach (XmlNode pastry in Nodelist)
                        {
                            if (pastry.ChildNodes[1].InnerText == Cost && pastry.LastChild.InnerText == off)//Neu cung ten banh, cung gia ban,cung sale off, thi cong don so luong
                            {

                                int temp = int.Parse(pastry.FirstChild.InnerText) + int.Parse(Quantity);

                                pastry.FirstChild.InnerText = temp.ToString();
                            }
                            else//cung ten banh, khac gia ban thi xem nhu tao 1 banh moi
                            {
                                XmlNode pastry1 = doc.CreateNode(XmlNodeType.Element, "pastry", null);
                                XmlAttribute namenode = doc.CreateAttribute("name");
                                XmlAttribute idcake = doc.CreateAttribute("idcake");
                                namenode.Value = Name;
                                idcake.Value = id_cake;
                                pastry1.Attributes.Append(namenode);
                                pastry1.Attributes.Append(idcake);
                                XmlNode Quantitynode = doc.CreateNode(XmlNodeType.Element, "quantity", null);
                                Quantitynode.InnerText = Quantity;
                                pastry1.AppendChild(Quantitynode);
                                XmlNode pricenode = doc.CreateNode(XmlNodeType.Element, "price", null);
                                pricenode.InnerText = Cost;
                                pastry1.AppendChild(pricenode);
                                XmlNode offnode = doc.CreateNode(XmlNodeType.Element, "saleoff", null);
                                offnode.InnerText = off;
                                pastry1.AppendChild(offnode);
                                Node.AppendChild(pastry1);
                            }
                        }

                    }
                    else//bánh này chưa có trong bàn
                    {
                        XmlNode pastry = doc.CreateNode(XmlNodeType.Element, "pastry", null);
                        XmlAttribute namenode = doc.CreateAttribute("name");
                        XmlAttribute idcake = doc.CreateAttribute("idcake");
                        namenode.Value = Name;
                        idcake.Value = id_cake;
                        pastry.Attributes.Append(namenode);
                        pastry.Attributes.Append(idcake);
                        XmlNode Quantitynode = doc.CreateNode(XmlNodeType.Element, "quantity", null);
                        Quantitynode.InnerText = Quantity;
                        pastry.AppendChild(Quantitynode);
                        XmlNode pricenode = doc.CreateNode(XmlNodeType.Element, "price", null);
                        pricenode.InnerText = Cost;
                        pastry.AppendChild(pricenode);
                        XmlNode offnode = doc.CreateNode(XmlNodeType.Element, "saleoff", null);
                        offnode.InnerText = off;
                        pastry.AppendChild(offnode);
                        Node.AppendChild(pastry);
                        //doc.Save("OnTable.xml");
                    }

                }
                doc.Save("OnTable.xml");
            }
            db.Clear();
            db1.Clear();


            dbTemp.Clear();
            string sQuery0 = "select b.MA_BANH, b.TEN_BANH, b.GIA_KINH_DOANH,s.SO_LUONG_TON_QUAY,s.NGAY_LEN_QUAY,s.NGAY_HET_HAN from banh b,san_pham_tai_quay s where b.MA_LOAI_BANH=1 and b.MA_BANH=s.MA_BANH;";
            string sQuery1 = "select b.MA_BANH, b.TEN_BANH, b.GIA_KINH_DOANH,s.SO_LUONG_TON_QUAY,s.NGAY_LEN_QUAY,s.NGAY_HET_HAN from banh b,san_pham_tai_quay s where b.MA_LOAI_BANH=2 and b.MA_BANH=s.MA_BANH;";
            //string sQuery2 = "select b.MA_BANH, b.TEN_BANH, b.GIA_KINH_DOANH,s.SO_LUONG_TON_QUAY,s.NGAY_LEN_QUAY,s.NGAY_HET_HAN from banh b,san_pham_tai_quay s where b.MA_LOAI_BANH=3 and b.MA_BANH=s.MA_BANH;";

            string sQuery4 = "select * from san_pham_tai_quay;";

            loadBanhFromMySQLtoDataTable(sQuery0, ref db);
            loadBanhFromMySQLtoDataTable(sQuery1, ref db1);
            //loadBanhFromMySQLtoDataTable(sQuery2, ref db2);
            loadBanhFromMySQLtoDataTable(sQuery4, ref dbTemp);
            ListviewLoad(db, false);
        }

        private void btn_movetoTable_Click(object sender, EventArgs e)
        {
            if (ReceiptDatagrid.RowCount < 1)
            {
                MessageBox.Show("Không có sản phẩm");
                return;
            }

            AddCaketo_table();
            CheckTables();
            addDB.Clear() ;

            }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;
            if (now.Hour >= 20 && now.Minute >= 30)
            {
                ReceiptDatagrid.Columns["Off%"].ReadOnly = false;
                lb_saleoff.Visible = true;
            }
        }

        private void btnListOrder_Click(object sender, EventArgs e)
        {
            DonDatHangForm objDonDatHang = new DonDatHangForm();
            objDonDatHang.Activate();
            objDonDatHang.Show();
        }
        //xoa bao cao ca
        private void DeleteReportsBtn_Click_1(object sender, EventArgs e)
        {

            if (MessageBox.Show("Bạn Có Muốn Xóa Báo Cáo Ca Không ?",
                                    "Báo Cáo Ca Đã Được Xóa",
                                    MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    string sCallXoaBaoCaoCa = "call xoa_bao_cao_ca(" + sMaNhanVien + ")";
                    cnn.excecuteQuery(sCallXoaBaoCaoCa);
                    MessageBox.Show("All reports are deleted");
                }
                catch (Exception error)
                {
                    objPrinter.logToFile("DeleteReportsBtn_Click Error: " + error.ToString());
                    MessageBox.Show("DeleteReportsBtn_Click Error: " + error.ToString());

                }
                //connection.Close();
            }
        }

        //Bao cao ca
        private void ShiftReportsBTN_Click_1(object sender, EventArgs e)
        {
            /*
            Ho to print bao cao ca! 
            * Search from Table: Hoa_Don, select chi_tiet_hoa_don
            * select 
            * where ma_nhan_vien =100 and ngay_lap_hoa_don ~ today.  
            * 
            * 
            */
            if (MessageBox.Show("Bạn Có Muốn In Báo Cáo Ca Không ?",
                                    "Báo Cáo Ca Đã Được In",
                                    MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load("temp.xml");
                XmlNode node = xmlDoc.SelectSingleNode("Pasteles/StartTime");
                string startTime = node.InnerText.ToString();

                DateTime currenTime = DateTime.Now;
                string sStartShift = startTime;
                string sCurrentTime = currenTime.ToString("yyyy-MM-dd HH:mm:ss");
                string sQuery_hoadon = "call bao_cao_ca_hoa_don(" + sMaNhanVien + ",'" + sStartShift + "','" + sCurrentTime + "')";
                string sQuery_banh = "call bao_cao_ca_banh(" + sMaNhanVien + ",'" + sStartShift + "','" + sCurrentTime + "')";

                string sStringToPrintHead = "##############################\r\n";
                sStringToPrintHead = sStringToPrintHead + "BAO CAO CA\r\n";
                sStringToPrintHead = sStringToPrintHead + "------------\r\n";
                sStringToPrintHead = sStringToPrintHead + "Nhan vien: " + sMaNhanVien + "\r\n";
                sStringToPrintHead = sStringToPrintHead + currenTime.ToShortDateString() + "\r\n";
                sStringToPrintHead = sStringToPrintHead + "------------\r\n";
                objPrinter.logToFile(sStringToPrintHead);
                objPrinter.safePrinting(sStringToPrintHead);
                string sMaHoaDon = "";
                string sMoney = "";
                string sDate = "";
                double lMoney = 0;
                try
                {
                    objPrinter.logToFile("start printing bao cao ca\r\n");
                    objPrinter.logToFile(sQuery_hoadon);
                    //connection.Open();
                    //MySqlDataAdapter myDA = new MySqlDataAdapter();
                    //myDA.SelectCommand = new MySqlCommand(sQuery_hoadon, connection);
                    //var dataReader = myDA.SelectCommand.ExecuteReader();
                    DataTable dtHoaDon = cnn.excecuteQueryToDataTable(sQuery_hoadon);
                    MessageBox.Show("Print bao cao OK!!! ");//xxx

                    //hoa don
                    //foreach (DataRow dr in dtHoaDon.Rows)
                    //{
                    //    try
                    //    {
                    //        sMaHoaDon = dr[0].ToString();
                    //        sMoney = dr[1].ToString();
                    //        lMoney = lMoney + Convert.ToDouble(sMoney);
                    //        //sDate = dataReader.GetString(2).Substring(0,10);
                    //        //sDate = dataReader.GetDateTime(2).ToString("HH:mm:ss");
                    //        sDate = Convert.ToDateTime(dr[2]).ToString("HH:mm:ss");
                    //        //sStringToPrint = sStringToPrint+"No:" + sMaHoaDon + ", " + sDate + "," +"$:"+ sMoney + "\r\n";  

                    //        //sStringToPrint = sStringToPrint + "No:" + sMaHoaDon + ", " + sDate + "," + "$:" + sMoney + "\r\n";
                    //        string sStringToPrintHD = objStringProcessor.stringReport(sMaHoaDon, sDate, sMoney) + "\r\n";
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        MessageBox.Show("Push data error: " + ex.ToString());
                    //    }
                    //}
                    //dataReader.Close();
                    //banh
                    DataTable dtBanh = cnn.excecuteQueryToDataTable(sQuery_banh);
                    objPrinter.logToFile(sQuery_banh);
                    string sTenBanh = "";
                    string sSoLuong = "";
                    string sTongTien = "";
                    string sStringToPrintDetails = "";
                    foreach (DataRow dr in dtBanh.Rows)
                    {
                        try
                        {
                            sTenBanh = dr[1].ToString();
                            sSoLuong = dr[2].ToString();
                            sTongTien = dr[3].ToString();

                            //sStringToPrint = sStringToPrint + sTenBanh + ", " + sSoLuong + "," + "$:" + sTongTien + "\r\n";
                            sStringToPrintDetails = objStringProcessor.stringReport(sTenBanh, sSoLuong, sTongTien) + "\r\n";
                            objPrinter.logToFile(sStringToPrintDetails+sStringToPrintDetails.Length.ToString());
                            objPrinter.safePrinting(sStringToPrintDetails);
                            lMoney = lMoney + Convert.ToDouble(sTongTien);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Push data error: " + ex.ToString());
                        }
                    }
                    string sStringToPrintSum = "";
                    sStringToPrintSum = sStringToPrintSum + "------------\r\n";
                    sStringToPrintSum = sStringToPrintSum + "Total sale: \r\n" + objStringProcessor.cutNo(lMoney.ToString()) + "\r\n";       
                    objPrinter.logToFile(sStringToPrintSum + sStringToPrintSum.Length.ToString());
                    objPrinter.safePrinting(sStringToPrintSum);
                }
                catch (Exception error)
                {
                    MessageBox.Show("Query Error: " + error.ToString());
                }
         
                //xoa bao cao ca
                try
                {
                    string sCallXoaBaoCaoCa = "call xoa_bao_cao_ca(" + sMaNhanVien + ")";
                    cnn.excecuteQuery(sCallXoaBaoCaoCa);
                    MessageBox.Show("All reports are deleted");
                    ReceiptsuptoNow = 0;//reset bien dem ve 0
                    lbl_ReceiptuptoNow.Text = "0";//hien thi tong hoa don trong ca ve 0

                }
                catch (Exception error)
                {
                    objPrinter.logToFile("DeleteReportsBtn_Click Error: " + error.ToString());
                    MessageBox.Show("DeleteReportsBtn_Click Error: " + error.ToString());

                }
            }
        }

    }
}